package com.xiaomo.gitee.datamanager;

import jakarta.validation.constraints.NotNull;
import lombok.Getter;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;


@Component
@Lazy(false)
@SuppressWarnings("unchecked")
public class SpringBeanUtils implements ApplicationContextAware, DisposableBean {
    @Getter
    private static ApplicationContext applicationContext = null;

    private SpringBeanUtils() {
    }

    public static <T> T getBean(String name) {
        return (T) applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> requiredType) {
        return applicationContext.getBean(requiredType);
    }

    //清除SpringContextHolder中的ApplicationContext:
    public static void clearHolder() {
        applicationContext = null;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringBeanUtils.applicationContext = applicationContext;
    }

    @Override
    public void destroy() throws Exception {
        clearHolder();
    }
}
